package com.kevin.utility.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.SizeLimitExceededException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.kevin.utility.entity.CommonResult;
import com.kevin.utility.enums.Charset;

/**
 * 文件操作类
 * 
 * @author juntao.lai
 * @since 2015年2月12日
 *
 */
public class FileUtil {
    
    private static Logger logger = Logger.getLogger(FileUtil.class);
    
    /**
     * 获取系统文件路径分隔符
     * 
     * @return
     */
    public static String getFileSeparator() {
        return File.separator;
    }
    
    /**
     * 读取文件内容
     * (默认使用UTF-8)
     * @param filePath
     * @return
     */
    public static String readFileContent(String filePath){
        return readFileContent(filePath, Charset.UTF8);
    }
    
    /**
     * 读取文件内容
     * 
     * @param filePath
     * @param charset
     * @return
     */
    public static String readFileContent(String filePath, Charset charset){
        File file = new File(filePath);
        if (!file.exists()){
            logger.error(String.format("路径[%s]不存在。", filePath));
            return null;
        }
        
        if (!file.isFile()){
            logger.error(String.format("路径[%s]不是一个文件。", filePath));
            return null;
        }
        
        if (!file.canRead()){
            logger.error(String.format("路径[%s]无法读取。", filePath));
            return null;
        }
        
        
        try {
            StringBuffer buffer = new StringBuffer();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charset.getText()));
            String line = "";
            while ((line = bufferedReader.readLine()) != null ){
                buffer.append(line).append("\n");
            }
            
            bufferedReader.close();
            
            logger.info(String.format("路径[%s]读取成功。", filePath));
            return buffer.toString();
        } catch (Exception ex){
            logger.error("读取文件[" + filePath + "]错误" + ex.getMessage());
            return null;
        }
    }
    
    
    /**
     * 文件/文件夹是否存在
     * 
     * @param filePath
     * @return
     */
    public static boolean isFilePathExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }
    
    /**
     * 删除文件或文件夹
     * 
     * @param file
     * @return
     */
    public static boolean deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                try {
                    if (!file.delete()) {
                        return false;
                    }
                } catch (Exception ex) {
                    logger.error(ex.getMessage());
                    return false;
                }
            } else if (file.isDirectory()){
                File[] files = file.listFiles();
                
                for (int i = 0; i < files.length; i++) {  
                    //删除子文件  
                    if (!deleteFile(files[i])){
                        return false;
                    }
                }
                
                //删除当前目录  
                try {
                    if (!file.delete()) {
                        return false;
                    }
                } catch (Exception ex) {
                    logger.error(ex.getMessage());
                    return false;
                }  
            }
        }
        return true;
    }
    
    /**
     * 创建文件
     * 
     * @param file
     * @return
     * @throws IOException
     */
    public static boolean createFile(File file) throws IOException {  
        if(! file.exists()) {  
            makeDir(file.getParentFile());  
        }  
        return file.createNewFile();  
    }
    
    /**
     * 新建目录
     * 
     * @param dir
     */
    public static void makeDir(File dir) {  
        if(! dir.getParentFile().exists()) {  
            makeDir(dir.getParentFile());  
        }
        if (!dir.exists()){
            dir.mkdir();
        }
    }
    
    public static String readContentFromInputStream(InputStream stream) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(stream));  
        String s="";  
        StringBuilder sb = new StringBuilder();
        while((s=br.readLine())!=null)  {
            sb.append(s);
        }
        return sb.toString();
    }
    
    public static long getFileSize(String path) {
    	return getFileSize(new File(path));
    }
    
    public static long getFileSize(File file) {
    	if (file.exists()) {
    		return file.length();
    	} else {
    		return (long)0;
    	}
    }
    
    /**
     * 重命名
     * 
     * @param oriFile
     * @param desFileName
     * @return
     */
    public static boolean rename(File oriFile, String desFileName) {
    	if (null == oriFile || !oriFile.exists() || oriFile.isDirectory()) {
    		logger.info("重命名失败，文件不存在。");
    		return false;
    	}
    	
    	File parent = oriFile.getParentFile();
    	String parentPath = parent.getPath();
    	String desPath = parentPath + desFileName;
    	return oriFile.renameTo(new File(desPath));
    }
    
    @SuppressWarnings("unchecked")
    
    
    /**
     * 拷贝文件夹
     * 
     * @param srcPath
     * @param desPath
     */
    public static void copyDir(String srcPath, String desPath) {  
        File file1=new File(srcPath);  
        File[] fs=file1.listFiles();  
        File file2=new File(desPath);  
        makeDir(file2);
        for (File f : fs) {  
            if(f.isFile()){  
            	copyFile(f.getPath(),desPath + getFileSeparator() + f.getName()); //调用文件拷贝的方法  
            }else if(f.isDirectory()){
            	copyDir(f.getPath(),desPath+getFileSeparator()+f.getName());  
            }
        }
    }  
  
    /** 
     * 文件拷贝 
     */  
    public static void copyFile(String src, String des) {  
    	File srcFile = new File(src);
    	File desFile = new File(des);
    	FileInputStream input = null;
    	FileOutputStream output = null;
    	try {
    		if (!srcFile.exists()) {
    			logger.info("源文件[" + src + "]不存在");
    			return;
    		}
    		input = new FileInputStream(srcFile);
    		
    		if (!desFile.exists()) {
    			createFile(desFile);
    		}
    		
    		output = new FileOutputStream(desFile);
    		byte[] temp = new byte[1000];
    		int size = input.read(temp);
    		
    		while (size != -1) {
    			output.write(temp);
    			size = input.read(temp);
    		}
    		logger.info("File copy finished.[" + src + "] --> [" + des + "]");
    	} catch (IOException ioe) {
    		logger.error(ioe.getMessage(), ioe);
    	} finally {
			try {
				input.close();
				output.close();
			} catch (Exception e) {
				logger.error("close stream error" + e.getMessage(), e);
			}
		}
    }
}
